package com.member.mp.web;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.core.domain.R;
import com.member.common.core.page.PageResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.SysBizOrder;
import com.member.shop.domain.SysBizOrderService;
import com.member.shop.domain.SysBizUser;
import com.member.shop.dto.ApplyAfterSaleDto;
import com.member.shop.dto.OrderServiceDto;
import com.member.shop.service.ISysBizOrderService;
import com.member.shop.service.ISysBizOrderServiceService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 【申请售后】控制器
 *
 * @author luoyun
 * @version 1.0
 * @date 2025/02/02
 **/
@RestController
@RequestMapping("/wx/after")
public class OrderAfterSaleController extends SupperController {

    @Resource
    private ISysBizOrderServiceService sysBizOrderServiceService;
    @Resource
    private ISysBizOrderService sysBizOrderService;

    /**
     * 售后详情
     *
     * @return
     */
    @PostMapping("/details/{id}")
    public R<SysBizOrderService> details(@PathVariable("id") Long id) {
        SysBizOrderService byId = sysBizOrderServiceService.getById(id);
        return R.ok(byId);
    }

    /**
     * 取消售后
     *
     * @return
     */
    @PostMapping("/cancel/{id}")
    public R<String> cancel(@PathVariable("id") Long id) {
        SysBizOrderService byId = sysBizOrderServiceService.getById(id);
        if (byId != null) {
            return R.fail("售后申请不存在");
        }
        if (!byId.getUserId().equals(id)) {
            return R.fail("非法请求");
        }
        sysBizOrderServiceService.deleteSysBizOrderServiceById(byId.getId());
        return R.ok();
    }

    /**
     * 售后列表（分页）
     *
     * @return
     */
    @RequestMapping("/list")
    public R<PageResult<SysBizOrderService>> list(OrderServiceDto orderServiceDto) {
        startPage();
        SysBizUser loginUser = getLoginUser();
        Long userId = loginUser.getId();
        LambdaQueryWrapper<SysBizOrderService> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysBizOrderService::getUserId, userId);
        if (StringUtils.isNotEmpty(orderServiceDto.getGoodsName())) {
            String keyword = "%" + orderServiceDto.getGoodsName() + "%";
            queryWrapper.apply("JSON_EXTRACT(goodsName, '$') LIKE {0}", keyword);
        }
        if(StringUtils.isNotEmpty(orderServiceDto.getStartDate()) && StringUtils.isNotEmpty(orderServiceDto.getEndDate())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                queryWrapper.between(SysBizOrderService::getApplyTime,sdf.parse(orderServiceDto.getStartDate()),sdf.parse(orderServiceDto.getEndDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<SysBizOrderService> orderServices = sysBizOrderServiceService.list(queryWrapper);

        TableDataInfo dataTable = getDataTable(orderServices);
        List<?> rows = dataTable.getRows();

        List<SysBizOrderService> collect = rows.stream().map(p -> (SysBizOrderService) p).collect(Collectors.toList());
        return R.ok(new PageResult<>(dataTable.getTotal(), collect));
    }

    /**
     * 提交售后申请
     *
     * @param applyAfterSaleDto 参数
     * @return 结果
     */
    @PostMapping("/applyAfterSale")
    public R<String> applyAfterSale(@RequestBody @Validated ApplyAfterSaleDto applyAfterSaleDto) {
        String orderId = applyAfterSaleDto.getOrderId();
        AtomicReference<BigDecimal> totalRefundAmountRef = new AtomicReference<>(BigDecimal.ZERO);

        SysBizOrder bizOrder = sysBizOrderService.getOne(new LambdaQueryWrapper<SysBizOrder>().eq(SysBizOrder::getUserId, getUserId()).eq(SysBizOrder::getId, orderId));

        if (bizOrder.getStatus() != 40) {
            logger.error("订单状态异常,暂不支持售后 bizOrder status:{}",bizOrder.getStatus());
            return R.fail("订单状态异常,暂不支持售后");
        }

        bizOrder.setStatus(80);
        sysBizOrderService.updateById(bizOrder);

        SysBizOrderService after = new SysBizOrderService();
        after.setOrderId(orderId);
        after.setGoodsInfo(applyAfterSaleDto.getGoodsInfo());
        after.setRefundAmount(totalRefundAmountRef.get());
        after.setUserId(getUserId());
        after.setApplyReason(applyAfterSaleDto.getApplyReason());
        after.setVoucherImages(applyAfterSaleDto.getVoucherImages());
        after.setRemark(applyAfterSaleDto.getRemark());
        after.setReturnReason(applyAfterSaleDto.getReturnReason());
        Snowflake snowflake = IdUtil.getSnowflake();
        after.setRefundNo(snowflake.nextIdStr());
        after.setRefundType(0L);
        after.setRefundTime(DateUtils.getNowDate());
        after.setRefundStatus(0L);
        after.setAuditStatus(0L);
        after.setOrderCode(applyAfterSaleDto.getOrderCode());
        after.setApplyTime(DateUtils.getNowDate());
        after.setUserName(StringUtils.isNotEmpty(getUsername())?getUsername():"");
        after.setUserPhone(StringUtils.isNotEmpty(getUserPhone())?getUserPhone():"");
        sysBizOrderServiceService.insertSysBizOrderService(after);

        return R.ok();
    }
}
